# coding=utf-8
import re
from time import sleep

from Page.base_page import *


class ProcessAgent(BasePage):

    def _get_search_result(self):
        """
        获取搜索结果
        :return:
        """
        # 等待搜索结果出来
        self.wait_for_visible('css', '.layui-table-body.layui-table-main>table tr')
        search_count = len(self.finds('css', '.layui-table-body.layui-table-main>table tr'))
        self.log.info(f"查询结果:{search_count}")
        return search_count

    def by_agent_user_search(self, user):
        """
        通过代理人或者用户名称搜索代理信息
        :param user:
        :return: 返回用户名称列的所有用户和代理人列的所有用户
        """
        self.input('name', 'name',user)
        self.click('id', 'easy_search_btn')
        self.wait_for_visible('css','.layui-laypage-count')
        text = self.find('css','.layui-laypage-count').text
        a=0
        # 可能出现进入代理列表，后搜索，但是结果还是之前的，没加载出搜索后的结果
        count = int(re.findall(r'\d+', text)[0])
        while count>=28 :
            a+=1
            text = self.find('css', '.layui-laypage-count').text
            count = int(re.findall(r'\d+', text)[0])
            print(f'搜索结果数量：{count}')
            sleep(1)
            if a==10:
                break
        tbody = '//*[@id="userTable"]//*[@class="layui-table-body layui-table-main"]//tbody'
        # 获取到第一页的查询结果数
        count = len(self.finds('xpath',f'{tbody}/tr'))
        user_list = []
        agent_list = []
        # 获取到用户名称列的所有用户名称和代理人列的所有用户名称
        for i in range(count):
            username = self.find('xpath',f'{tbody}/tr[{i+1}]/td[@data-field="UserName"]').get_attribute('title')
            agent = self.find('xpath',f'{tbody}/tr[{i+1}]/td[@data-field="AgentName"]').get_attribute('title')
            user_list.append(username)
            agent_list.append(agent)
        return user_list, agent_list

    def open_showDetail(self,user,field_list):
        self.by_agent_user_search(user)
        self.find('css','.layui-table-body.layui-table-main a[lay-event="showDetail"]')
        self.execute_js('$(\'.layui-table-body.layui-table-main a[lay-event="showDetail"]\').click()')
        self.wait_for_visible('css','.layui-layer-title')
        self.until_switch_frame_success('xpath','//iframe[contains(@src,"/backend/processlist/NewAgentDialog-show")]')
        field_values = []
        for field in field_list:
            text = self.find('xpath',f'//label[contains(text(),"{field}")]//following-sibling::div').text
            field_values.append(text)
        return field_values

